package com.helasasa.maxfunds.lineofcredit.cashloan.cameroon.screen.proof

import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.helasasa.maxfunds.lineofcredit.cashloan.ProjectApplication
import com.helasasa.maxfunds.lineofcredit.cashloan.cameroon.http.IApiProcessCameroonCallback
import com.helasasa.maxfunds.lineofcredit.cashloan.cameroon.http.createApiActionCameroon
import com.helasasa.maxfunds.lineofcredit.cashloan.cameroon.http.doPostRequestCameroon
import com.helasasa.maxfunds.lineofcredit.cashloan.cameroon.user.mainProcessFormatCameroon
import com.helasasa.maxfunds.lineofcredit.cashloan.cameroon.user.nextRenderCameroon
import com.google.gson.JsonObject
import org.json.JSONArray
import org.json.JSONObject

class ProofCameroonViewModel : ViewModel() {

    private val _loadingResult = MutableLiveData<Boolean>()
    val loadingResult: LiveData<Boolean> = _loadingResult

    private val _pageDetailResult = MutableLiveData<ProofCameroonResult>()
    val pageDetailResult: LiveData<ProofCameroonResult> = _pageDetailResult

    private val _saveStepResult = MutableLiveData<ProofCameroonSaveStepResult>()
    val saveStepResult: LiveData<ProofCameroonSaveStepResult> = _saveStepResult

    private val _mainProcessResult = MutableLiveData<ProofCameroonMainProcessResult>()
    val mainProcessResult: LiveData<ProofCameroonMainProcessResult> = _mainProcessResult

    private val _nextRouterResult =
        MutableLiveData<ProofCameroonNextRouterResult<AppCompatActivity>>()
    val nextRouterResult: LiveData<ProofCameroonNextRouterResult<AppCompatActivity>> =
        _nextRouterResult

    private var stepIndex = 0

    /** 获取页面详情接口 */
    fun pageDetail() {
        _loadingResult.value = true
        val context = ProjectApplication.context
        val action = hashMapOf<String, Any>().createApiActionCameroon()
        action["path"] = "D50PrK3UELaosdHcVCL7A"

        context.doPostRequestCameroon(action, object : IApiProcessCameroonCallback {
            override fun onApiReady() {
            }

            override fun onApiDone(jsonObject: JSONObject) {
                _loadingResult.value = false

                val obj = jsonObject.optJSONObject("obj") ?: JSONObject()
                renderPageItems(obj)
            }

            override fun onApiError(code: String, errMsg: String) {
                _loadingResult.value = false

                _pageDetailResult.value = ProofCameroonResult(error = errMsg)
            }
        })
    }

    /** 查询主流程接口 */
    fun mainProcess() {
        _loadingResult.value = true

        val context = ProjectApplication.context
        val action = hashMapOf<String, Any>().createApiActionCameroon()
        action["path"] = "D50PrK3UELaosdHcVCL7A"

        context.doPostRequestCameroon(action, object : IApiProcessCameroonCallback {
            override fun onApiReady() {
            }

            override fun onApiDone(jsonObject: JSONObject) {
                _loadingResult.value = false

                val obj = jsonObject.optJSONObject("obj")
                _mainProcessResult.value = ProofCameroonMainProcessResult(success = obj)
            }

            override fun onApiError(code: String, errMsg: String) {
                _loadingResult.value = false

                _mainProcessResult.value = ProofCameroonMainProcessResult(error = errMsg)
            }
        })
    }

    /**
     * 保存认证信息
     */
    fun saveStepInfo() {
        val pageDetails = _pageDetailResult.value
        val apiUrl = pageDetails?.apiUrl ?: ""
        val pageTitle = pageDetails?.pageTitle ?: ""
        val items = pageDetails?.items ?: emptyList()
        if (apiUrl.isNotBlank()) {
            // 网络请求接口参数
            val action = hashMapOf<String, Any>().createApiActionCameroon()
            if (pageTitle.contains("Contact", true)) {
                // 组装信息-联系人
                val contactParamName = if (items.isNotEmpty()) {
                    items[0].optString("paramName")
                } else ""

                if (contactParamName.isNotBlank()) {
                    val rowParams = mutableListOf<JsonObject>()
                    var tidex = 0
                    for (row in items) {
                        tidex += 1
                        val dataList = (row["dataList"] ?: JSONArray()) as JSONArray
                        val rowApiHashMap = JsonObject()
                        for (di in 0 until dataList.length()) {
                            tidex += 1
                            val element = dataList[di] as JSONObject
                            val paramName = element.optString("paramName")
                            val content = element.optString("realContent")
                            if (content.isBlank()) {
                                _saveStepResult.value =
                                    ProofCameroonSaveStepResult(error = "Please fill all items")
                                return
                            }
                            if (paramName.isNotBlank()) {
                                rowApiHashMap.addProperty(paramName, content)
                            }
                        }
                        rowParams.add(rowApiHashMap)
                    }
                    action[contactParamName] = rowParams
                }

            } else {
                // 组装信息-正常列表
                for (element in items) {
                    val paramName = element.optString("paramName")
                    val content = element.optString("realContent")
                    val isMust = element.optString("isMust")
                    if (content.isBlank()) {
                        if (!isMust.contains("NO", true)) {
                            _saveStepResult.value =
                                ProofCameroonSaveStepResult(error = "Please fill all items")
                            return
                        }
                    }
                    if (paramName.isNotBlank()) {
                        action[paramName] = content
                    }
                }
            }

            _loadingResult.value = true

            // 网络请求
            val context = ProjectApplication.context
            action["path"] = apiUrl

            context.doPostRequestCameroon(action, object : IApiProcessCameroonCallback {
                override fun onApiReady() {
                }

                override fun onApiDone(jsonObject: JSONObject) {
                    _loadingResult.value = false
                    mainProcess()
                }

                override fun onApiError(code: String, errMsg: String) {
                    _loadingResult.value = false

                    _saveStepResult.value = ProofCameroonSaveStepResult(error = errMsg)
                }
            })
        } else {
            _saveStepResult.value = ProofCameroonSaveStepResult(error = "Please fill all items")
        }
    }

    /**
     * 渲染列表
     */
    fun renderPageItems(jsonObject: JSONObject) {
        val nextRenders = jsonObject.nextRenderCameroon()
        val needOcr = (nextRenders["needOcr"] ?: false) as Boolean
        val needFace = (nextRenders["needFace"] ?: false) as Boolean
        val needWallet = (nextRenders["needWallet"] ?: false) as Boolean
        val step = (nextRenders["step"] ?: "") as String
        val pageTitle = (nextRenders["pageTitle"] ?: "") as String
        val apiUrl = (nextRenders["apiUrl"] ?: "") as String
        val items =
            ((nextRenders["dataList"] ?: emptyList<JSONObject>()) as List<JSONObject>)
        val headers =
            ((nextRenders["headers"] ?: emptyList<JSONObject>()) as List<JSONObject>)
        println(headers)

        // 判断是否要跳转
        if (needOcr or needFace or needWallet or items.isEmpty()) {
            nextRouter(jsonObject)
        } else {
            _pageDetailResult.value = ProofCameroonResult(
                step = step,
                pageTitle = pageTitle,
                headers = headers,
                items = items,
                apiUrl = apiUrl
            )
        }
    }

    /**
     * 更新选择日期数据
     */
    fun selectedDate(date: String, tid: String) {
        val pageTitle = _pageDetailResult.value?.pageTitle
        val apiUrl = _pageDetailResult.value?.apiUrl
        val headers = _pageDetailResult.value?.headers
        val items = _pageDetailResult.value?.items ?: emptyList()

        for (element in items) {
            val paramName = element.optString("paramName")
            if (paramName == tid) {
                element.put("content", date)
                element.put("realContent", date)
            }
        }

        // 更新页面
        _pageDetailResult.value = ProofCameroonResult(
            pageTitle = pageTitle,
            headers = headers,
            items = items,
            apiUrl = apiUrl
        )
    }

    /** 页面跳转 */
    fun nextRouter(jsonObject: JSONObject) {
        // 判断下一步
        val nextRouterResult = jsonObject.mainProcessFormatCameroon(fromProof = true)
        if (nextRouterResult.nextRouter != null) {
            _nextRouterResult.value =
                ProofCameroonNextRouterResult(nextPage = nextRouterResult.nextRouter)
        }
    }
}